package com.cbtx.utils

import android.app.Application
import android.os.Environment
import android.text.TextUtils
import com.blankj.utilcode.util.LogUtils
import java.io.*
import java.text.DecimalFormat
import java.util.*

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/1 2:02 PM
 * desc   :
 */
object FileUtil {

    var ROOT_DIR = "cbtx"
    const val DOWNLOAD_DIR = "download"
    const val CACHE_DIR = "cache"
    const val ICON_DIR = "icon"
    const val CHAT_DIR = "chat"
    const val AVATAR_DIR = "avatar"

    lateinit var mContext: Application

    fun init(application: Application) {
        mContext = application
    }

    /** 判断SD卡是否挂载  */
    fun isSDCardAvailable(): Boolean {
        return Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()
    }

    /** 获取下载目录  */
    fun getDownloadDir(): String? {
        return getDir(DOWNLOAD_DIR)
    }

    /** 获取缓存目录  */
    fun getCacheDir(): String? {
        return getDir(CACHE_DIR)
    }

    /** 获取icon目录  */
    fun getIconDir(): String? {
        return getDir(ICON_DIR)
    }

    /** 获取自己定义的目录  */
    fun getCustomDir(path: String?): String? {
        return getDir(path)
    }

    /** 获取chat目录  */
    fun getChatDir(): String? {
        return getDir(CHAT_DIR)
    }

    /** 获取avatar目录  */
    fun getAvatarDir(): String? {
        return getDir(AVATAR_DIR)
    }

    /** 获取应用目录，当SD卡存在时，获取SD卡上的目录，当SD卡不存在时，获取应用的cache目录  */
    fun getDir(name: String?): String? {
        val sb = StringBuilder()
        if (isSDCardAvailable()) {
            sb.append(getExternalStoragePath())
        } else {
            sb.append(getCachePath())
        }
        sb.append(name)
        sb.append(File.separator)
        val path = sb.toString()
        return if (createDirs(path)) {
            path
        } else {
            null
        }
    }

    /** 获取SD下的应用目录  */
    fun getExternalStoragePath(): String {
        val sb = StringBuilder()
        sb.append(Environment.getExternalStorageDirectory().absolutePath)
        sb.append(File.separator)
        sb.append(ROOT_DIR)
        sb.append(File.separator)
        return sb.toString()
    }

    /** 获取应用的cache目录  */
    fun getCachePath(): String? {
        val f = mContext!!.cacheDir
        return if (null == f) {
            null
        } else {
            f.absolutePath + "/"
        }
    }

    /** 创建文件夹  */
    fun createDirs(dirPath: String?): Boolean {
        val file = File(dirPath)
        return if (!file.exists() || !file.isDirectory) {
            file.mkdirs()
        } else true
    }

    /** 复制文件，可以选择是否删除源文件  */
    fun copyFile(
        srcPath: String?, destPath: String?,
        deleteSrc: Boolean
    ): Boolean {
        val srcFile = File(srcPath)
        val destFile = File(destPath)
        return copyFile(srcFile, destFile, deleteSrc)
    }

    /** 复制文件，可以选择是否删除源文件  */
    fun copyFile(
        srcFile: File, destFile: File?,
        deleteSrc: Boolean
    ): Boolean {
        if (!srcFile.exists() || !srcFile.isFile) {
            return false
        }
        var `in`: InputStream? = null
        var out: OutputStream? = null
        try {
            `in` = FileInputStream(srcFile)
            out = FileOutputStream(destFile)
            val buffer = ByteArray(1024)
            var i = -1
            while (`in`.read(buffer).also { i = it } > 0) {
                out.write(buffer, 0, i)
                out.flush()
            }
            if (deleteSrc) {
                srcFile.delete()
            }
        } catch (e: Exception) {
            LogUtils.e(e)
            return false
        } finally {
            IOUtil.close(out)
            IOUtil.close(`in`)
        }
        return true
    }

    /** 判断文件是否可写  */
    fun isWriteable(path: String?): Boolean {
        return try {
            if (TextUtils.isEmpty(path)) {
                return false
            }
            val f = File(path)
            f.exists() && f.canWrite()
        } catch (e: Exception) {
            LogUtils.e(e)
            false
        }
    }

    /** 修改文件的权限,例如"777"等  */
    fun chmod(path: String, mode: String) {
        try {
            val command = "chmod $mode $path"
            val runtime = Runtime.getRuntime()
            runtime.exec(command)
        } catch (e: Exception) {
            LogUtils.e(e)
        }
    }

    /**
     * 把数据写入文件
     *
     * @param is
     * 数据流
     * @param path
     * 文件路径
     * @param recreate
     * 如果文件存在，是否需要删除重建
     * @return 是否写入成功
     */
    fun writeFile(
        `is`: InputStream?, path: String?,
        recreate: Boolean
    ): Boolean {
        var res = false
        val f = File(path)
        var fos: FileOutputStream? = null
        try {
            if (recreate && f.exists()) {
                f.delete()
            }
            if (!f.exists() && null != `is`) {
                val parentFile = File(f.parent)
                parentFile.mkdirs()
                var count = -1
                val buffer = ByteArray(1024)
                fos = FileOutputStream(f)
                while (`is`.read(buffer).also { count = it } != -1) {
                    fos.write(buffer, 0, count)
                }
                res = true
            }
        } catch (e: Exception) {
            LogUtils.e(e)
        } finally {
            IOUtil.close(fos)
            IOUtil.close(`is`)
        }
        return res
    }

    /**
     * 把字符串数据写入文件
     *
     * @param content
     * 需要写入的字符串
     * @param path
     * 文件路径名称
     * @param append
     * 是否以添加的模式写入
     * @return 是否写入成功
     */
    fun writeFile(content: ByteArray?, path: String?, append: Boolean): Boolean {
        var res = false
        val f = File(path)
        var raf: RandomAccessFile? = null
        try {
            if (f.exists()) {
                if (!append) {
                    f.delete()
                    f.createNewFile()
                }
            } else {
                f.createNewFile()
            }
            if (f.canWrite()) {
                raf = RandomAccessFile(f, "rw")
                raf.seek(raf.length())
                raf.write(content)
                res = true
            }
        } catch (e: Exception) {
            LogUtils.e(e)
        } finally {
            IOUtil.close(raf)
        }
        return res
    }

    /**
     * 把字符串数据写入文件
     *
     * @param content
     * 需要写入的字符串
     * @param path
     * 文件路径名称
     * @param append
     * 是否以添加的模式写入
     * @return 是否写入成功
     */
    fun writeFile(content: String, path: String?, append: Boolean): Boolean {
        return writeFile(content.toByteArray(), path, append)
    }

    /**
     * 把键值对写入文件
     *
     * @param filePath
     * 文件路径
     * @param key
     * 键
     * @param value
     * 值
     * @param comment
     * 该键值对的注释
     */
    fun writeProperties(
        filePath: String?, key: String?,
        value: String?, comment: String?
    ) {
        if (TextUtils.isEmpty(key) || TextUtils.isEmpty(filePath)) {
            return
        }
        var fis: FileInputStream? = null
        var fos: FileOutputStream? = null
        val f = File(filePath)
        try {
            if (!f.exists() || !f.isFile) {
                f.createNewFile()
            }
            fis = FileInputStream(f)
            val p = Properties()
            p.load(fis) // 先读取文件，再把键值对追加到后面
            p.setProperty(key, value)
            fos = FileOutputStream(f)
            p.store(fos, comment)
        } catch (e: Exception) {
            LogUtils.e(e)
        } finally {
            IOUtil.close(fis)
            IOUtil.close(fos)
        }
    }

    /** 根据值读取  */
    fun readProperties(
        filePath: String?, key: String?,
        defaultValue: String?
    ): String? {
        if (TextUtils.isEmpty(key) || TextUtils.isEmpty(filePath)) {
            return null
        }
        var value: String? = null
        var fis: FileInputStream? = null
        val f = File(filePath)
        try {
            if (!f.exists() || !f.isFile) {
                f.createNewFile()
            }
            fis = FileInputStream(f)
            val p = Properties()
            p.load(fis)
            value = p.getProperty(key, defaultValue)
        } catch (e: IOException) {
            LogUtils.e(e)
        } finally {
            IOUtil.close(fis)
        }
        return value
    }

    /** 把字符串键值对的map写入文件  */
    fun writeMap(
        filePath: String?, map: Map<String?, String?>?,
        append: Boolean, comment: String?
    ) {
        if (map == null || map.size == 0 || TextUtils.isEmpty(filePath)) {
            return
        }
        var fis: FileInputStream? = null
        var fos: FileOutputStream? = null
        val f = File(filePath)
        try {
            if (!f.exists() || !f.isFile) {
                f.createNewFile()
            }
            val p = Properties()
            if (append) {
                fis = FileInputStream(f)
                p.load(fis) // 先读取文件，再把键值对追加到后面
            }
            p.putAll(map)
            fos = FileOutputStream(f)
            p.store(fos, comment)
        } catch (e: Exception) {
            LogUtils.e(e)
        } finally {
            IOUtil.close(fis)
            IOUtil.close(fos)
        }
    }

    /** 把字符串键值对的文件读入map  */
//    fun readMap(filePath: String?, defaultValue: String): MutableMap<String, String>?{
//        if (TextUtils.isEmpty(filePath)) {
//            return null
//        }
//        var map: MutableMap<String, String>? = null
//        var fis: FileInputStream? = null
//        val f = File(filePath)
//        try {
//            if (!f.exists() || !f.isFile) {
//                f.createNewFile()
//            }
//            fis = FileInputStream(f)
//            val p = Properties()
//            p.load(fis)
//            map = mutableMapOf<String, String>(p as MutableMap<String, String>) // 因为properties继承了map，所以直接通过p来构造一个map
//        } catch (e: Exception) {
//            LogUtils.e(e)
//        } finally {
//            IOUtils.close(fis)
//        }
//        return map
//    }

    /** 改名  */
    fun copy(src: String?, des: String?, delete: Boolean): Boolean {
        val file = File(src)
        if (!file.exists()) {
            return false
        }
        val desFile = File(des)
        var `in`: FileInputStream? = null
        var out: FileOutputStream? = null
        try {
            `in` = FileInputStream(file)
            out = FileOutputStream(desFile)
            val buffer = ByteArray(1024)
            var count = -1
            while (`in`.read(buffer).also { count = it } != -1) {
                out.write(buffer, 0, count)
                out.flush()
            }
        } catch (e: Exception) {
            LogUtils.e(e)
            return false
        } finally {
            IOUtil.close(`in`)
            IOUtil.close(out)
        }
        if (delete) {
            file.delete()
        }
        return true
    }

    /**
     * 获取文件夹大小
     *
     * @param file
     * File实例
     * @return long
     */
    fun getFolderSize(file: File): Long {
        var size: Long = 0
        try {
            val fileList = file.listFiles()
            for (i in fileList.indices) {
                size = if (fileList[i].isDirectory) {
                    size + getFolderSize(fileList[i])
                } else {
                    size + fileList[i].length()
                }
            }
        } catch (e: Exception) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        }
        // return size/1048576;
        return size
    }

    /**
     * 转换文件大小
     *
     * @param file
     * @return
     */
    fun formetFileSize(file: Long): String? {
        val df = DecimalFormat("#.00")
        var fileSizeString = ""
        val wrongSize = "0M"
        if (file == 0L) {
            return wrongSize
        }
        fileSizeString = if (file < 1024) {
            df.format(file.toDouble()) + "B"
        } else if (file < 1048576) {
            df.format(file.toDouble() / 1024) + "KB"
        } else if (file < 1073741824) {
            df.format(file.toDouble() / 1048576) + "MB"
        } else {
            df.format(file.toDouble() / 1073741824) + "GB"
        }
        return fileSizeString
    }

    /** 删除文件  */
    fun deleteFile(file: File) {
        if (file.exists()) { // 判断文件是否存在
            if (file.isFile) { // 判断是否是文件
                file.delete() // delete()方法 你应该知道 是删除的意思;
            } else if (file.isDirectory) { // 否则如果它是一个目录
                val files = file.listFiles() // 声明目录下所有的文件 files[];
                for (i in files.indices) { // 遍历目录下所有的文件
                    deleteFile(files[i]) // 把每个文件 用这个方法进行迭代
                }
            }
            file.delete()
        } else {
        }
    }
}